<?php
include_once "db.php";

use DataBase\Db;

class Contact
{
    private $conn;

    function __construct()
    {
        $db = new DataBase\Db();
        $this->conn = $db->connet();
    }

    function insert($a, $b, $c, $d, $icon)
    {
        if (isset($icon)) {
            move_uploaded_file($icon['tmp_name'], './' . $icon['name']);
            $icon = './' . $icon['name'];
        }

        if (!isset($a) || empty($a)) {
            exit("请输入联系人姓名");
        }

        if (!isset($b) || empty($b)) {
            exit("请输入联系人手机");
        }

        if (!isset($c) || empty($c)) {
            exit("请输入联系人qq");
        }

        if (isset($d)) {
            $sql = "update contact set `name`='$a',`mobile`='$b',`qq`='$c',`icon`='$icon' where id='$d'";
        } else {
            $sql = "insert into contact(`name`,`mobile`,`qq`,`icon`) values('$a','$b','$c','$icon');";
        }
        $sqls = $this->conn->prepare($sql);
        $ok = $sqls->execute();
        if ($ok) {
            if (isset($d)) {
                exit("修改成功");
            } else {
                exit("添加成功");
            }

        } else {
            exit("执行失败！");
        }
    }

    function del($id){
        if (!isset($id)) {
            exit('联系人id不能为空');
        }
        $sql = "delete from contact where id=$id";
        $sqls = $this->conn->prepare($sql);
        $ok = $sqls->execute();
        if(!$ok) exit ('数据服务暂时不可用');

        echo "删除成功";
    }

    function getcontact($id){
        if (!isset($id)) {
            exit('联系人id不能为空');
        }

        $sql = "select * from contact where id=$id;";
        $sqls = $this->conn->prepare($sql);
        $ok = $sqls->execute();
        if ($ok) {
            $contact = $sqls->fetch();
        } else {
            echo "数据服务暂时不可用";
        }
        return $contact;
    }

    function getLx($keyword){
        $sql = "select * from contact";
        if (isset($keyword)) {
            $sql = "select * from contact where `name` like '%$keyword%'";
        }
        $sqls = $this->conn->prepare($sql);
        $ok = $sqls->execute();
        if ($ok) {
            $list = $sqls->fetchAll();
        }
        return $list;
    }
}